{% extends 'template/jhTemplateV4.html'%}

{% block vueTemplate %}


<script id="app-template" type="text/html">
<div>
<v-app mobile-breakpoint="sm">
  <jh-menu />
  <v-main class="mt-15">
    <!-- 头部内容 >>>>>>>>>>>>> -->
    <div class="jh-page-second-bar px-8">
      <v-row>
        <v-col cols="4" xs="12" sm="12" md="4" xl="3">
          <div class="pt-3 text-h7 font-weight-bold">车辆保养管理
            <!-- 帮助页按钮 -->
            <v-icon @click="isHelpPageDrawerShown = true" color="success" small>mdi-help-circle-outline
            </v-icon>
          </div>
          <v-breadcrumbs class="pb-3 pt-0 pl-0" :items="breadcrumbs" divider="-"></v-breadcrumbs>
        </v-col>
        <!-- 搜索条件表单 >>>>>>>> -->
        <v-col cols="12" xs="12" sm="12" md="8" xl="9">
          <v-row class="jh-backend-form-container justify-end ma-0 py-1 pb-xs-2">
            <v-col cols="12" xs="6" sm="6" md="2" xl="3" class="pa-xs-0 pb-2 pl-1 pl-xs-1">
              <v-autocomplete v-model="serverSearchInput.status" color="success" prefix="保养状态:" class="jh-v-input bg-white" :items="constantObj.status" clearable dense filled single-line></v-autocomplete>
            </v-col>
            <v-col cols="12" xs="6" sm="6" md="3" xl="3" class="pa-xs-0 pb-2 pl-1 pl-xs-1">
              <v-autocomplete v-model="serverSearchInput.carNumber" color="success" prefix="车牌号:" class="jh-v-input bg-white" :items="this.tableData.map(row=>row.carNumber)" clearable dense filled single-line></v-autocomplete>
            </v-col>
            <v-col cols="12" xs="6" sm="6" md="3" xl="3" class="pa-xs-0 pb-2 pl-1 pl-xs-1">
              <range-picker :hasbutton="false" backgroundcolor="#fff" ref="rangePicker"></range-picker>
            </v-col>
    
            <!-- <v-col cols="12" xs="6" sm="6" md="3" xl="3" class="pa-xs-0 pb-2 pl-1 pl-xs-1">
              <v-menu class="jh-v-input" transition="scale-transition" offset-y min-width="auto">
                <template v-slot:activator="{on, attrs}">
                    <v-text-field v-bind="attrs" v-on="on" v-model="startDate" class="jh-v-input bg-white" dense clearable
                        single-line filled readonly label="点击此处选择查询起始日期"></v-text-field>
                </template>
                <v-date-picker color="success" elevation="20" v-model="startDate"></v-date-picker>
              </v-menu>
            </v-col>
            <v-col cols="12" xs="6" sm="6" md="3" xl="3" class="pa-xs-0 pb-2 pl-1 pl-xs-1">
              <v-menu class="jh-v-input" transition="scale-transition" offset-y min-width="auto">
                <template v-slot:activator="{on, attrs}">
                    <v-text-field v-bind="attrs" v-on="on" v-model="endDate" class="jh-v-input bg-white" dense clearable
                        single-line filled readonly label="点击此处选择查询终止日期"></v-text-field>
                </template>
                <v-date-picker color="success" elevation="20" v-model="endDate"></v-date-picker>
              </v-menu>
            </v-col> -->
            <v-btn class="jh-backend-search-btn elevation-0 ml-0 mt-3" color="success" small @click="doUiAction('getTableData')">
              查询
            </v-btn>
          </v-row>
        </v-col>
        <!-- <<<<<<<< 搜索条件表单 -->
      </v-row>
    </div>
    <!-- <<<<<<<<<<<<< 头部内容 -->

    <div class="jh-page-body-container px-8">
      <!-- 页面内容 >>>>>>>>>>>>> -->
      <v-card class="rounded-lg">
        <v-row class="ma-0 pa-4">
          <!-- 新增按钮 -->
          <v-btn color="success" class="elevation-0 mr-2" @click="doUiAction('startCreateItem')" small>新增</v-btn>
          <v-btn color="success" class="elevation-0 mr-2" @click="doUiAction('createPaymentRequest', {})" small
								>批量付款申请
							</v-btn>
          <!-- <v-btn color="success" class="elevation-0 mr-2" @click="exportExcel" small>导出excel</v-btn> -->
          <v-menu bottom offset-y>
            <template v-slot:activator="{ on, attrs }">
              <v-btn class="elevation-0 mr-2 custom" color="#2196F3" v-bind="attrs" v-on="on" small>
                导出
              </v-btn>
            </template>
            <v-list>
              <v-list-item v-for="(item, i) in exportItems" :key="i" @click="exportData(item.type)">
                <v-list-item-title>{{ item.text }}</v-list-item-title>
              </v-list-item>
            </v-list>
          </v-menu>
          <v-spacer></v-spacer>
          <!-- 搜索过滤 -->
          <v-col cols="12" xs="8" sm="4" md="3" xl="2" class="pa-0">
            <v-text-field color="success" v-model="searchInput" prefix="搜索：" class="jh-v-input" dense filled single-line></v-text-field>
          </v-col>
        </v-row>
        <!-- 表格 -->
        <v-data-table
          show-select item-key="maintenanceId" @item-selected="tableItemSelected" v-model="tableSelected" @toggle-select-all="tableToggleSelectAll"
          :headers="headers"
          :items="tableData"
          :search="searchInput"
          :footer-props="{ itemsPerPageOptions: [20, 50, -1], itemsPerPageText: '每页', itemsPerPageAllText: '所有'}"
          :items-per-page="-1"
          mobile-breakpoint="0"
          :loading="isTableLoading"
          checkbox-color="success"
          :class="{'zebraLine': isTableZebraLineShown }"
          fixed-header
          class="jh-fixed-table-height elevation-0 mt-0 mb-xs-4">
          <template v-slot:item.payment="{item}">
            <template v-for="(ticketItem, ticketIndex) in item.maintenancePaymentTicket">
              <div :key="ticketIndex">
                <span @click="doUiAction('updatePaymentRequest', ticketItem)" role="button" class="success--text font-weight-medium font-size-2 pr-2">申请_{{ticketItem.ticketRequestAt | mdFormat}}</span>
                <span v-if="ticketItem.ticketStatus !== '申请'" @click="doUiAction('viewPaymentRequest', ticketItem)" role="button" class="success--text font-weight-medium font-size-2">付款{{ticketItem.ticketStatus}}_{{ticketItem.ticketStatusAt | mdFormat}}</span>
              </div>
            </template>
          </template>

          <template v-slot:item.operationAt="{ item }">{{item.operationAt | dateFormat }}</template>
          <!-- 表格操作按钮 -->
          <template v-slot:item.action="{ item }">
            <span role="button" class="success--text font-weight-medium font-size-2 mr-2" @click="doUiAction('startUpdateItem', item)">
              <v-icon size="16" class="success--text">mdi-note-edit-outline</v-icon>修改
            </span>
            <span role="button" class="success--text font-weight-medium font-size-2 mr-2" @click="doUiAction('deleteItem', item)">
              <v-icon size="16" class="success--text">mdi-trash-can-outline</v-icon>删除
            </span>
            <!-- <span role="button" class="success--text font-weight-medium font-size-2 mr-2" @click="doUiAction('startFlowRequest', item)" v-if="item.status!=='已完成'">
              <v-icon size="16" class="success--text">mdi-wrench-clock</v-icon>付款申请
            </span>
            <span role="button" class="success--text font-weight-medium font-size-2" @click="doUiAction('completeMaintenance', item)" v-if="item.status==='保养中'">
              <v-icon size="16" class="success--text">mdi-timer-sand-complete</v-icon>完成
            </span> -->
            <v-menu offset-y v-if="item.status!=='已完成'">
              <template v-slot:activator="{ on, attrs }">
                <span
                  role="button"
                  class="success--text font-weight-medium font-size-2 mr-1"
                  v-bind="attrs"
                  v-on="on">
                  操作<v-icon size="14" class="success--text">mdi-chevron-down</v-icon>
                </span>
              </template>
              <v-list dense>
                <v-list-item
                  v-for="tableButton of tableButtonList"
                  @click="doUiAction(tableButton.action, {item, button: tableButton})">
                  <v-list-item-title> {{ tableButton.text }}</v-list-item-title>
                </v-list-item>
              </v-list>
            </v-menu>
          </template>
          <!-- 没有数据 -->
          <template v-slot:loading>
            <div class="jh-no-data">数据加载中</div>
          </template>
          <template v-slot:no-data>
            <div class="jh-no-data">暂无数据</div>
          </template>
          <template v-slot:no-results>
            <div class="jh-no-data">暂无数据</div>
          </template>
          <!-- 表格分页 -->
          <template v-slot:footer.page-text="pagination">
            <span>{{pagination.pageStart}}-{{pagination.pageStop}}</span>
            <span class="ml-1">共{{pagination.itemsLength}}条</span>
          </template>
          <template v-slot:item.remindDaysText="{ item }">
            <span :class="{'green--text' :item.remindDays > 3 , 'red--text': item.remindDays <= 3}">{{item.remindDaysText}}</span>
          </template>
        </v-data-table>
      </v-card>

            
      <!-- 保养付款申请抽屉 -->
      <drawer-createTicket ref="createFlowTicket" :ticketType="'flow'"></drawer-createTicket>
      
      <!-- 新增抽屉 -->
      <v-navigation-drawer v-if="isCreateDrawerShown" v-model="isCreateDrawerShown" :permanent="isCreateDrawerShown" fixed temporary right width="80%" class="elevation-24">
        <v-form ref="createForm" lazy-validation>
          <!-- 抽屉标题 -->
          <v-row>
            <span class="text-subtitle-1 font-weight-medium pa-6 pl-7">新增信息</span>
          </v-row>
          <!-- 抽屉表单 -->
          <!-- <v-text-field class="jh-v-input" dense single-line filled v-model="createItem.xxxId" :rules="validationRules.requireRules"></v-text-field> -->
          <v-row class="mt-0 px-4">
            
            <car-number-select @success="doInsertInCreateItem"></car-number-select>
             
            <v-col cols="12" sm="12" md="4">
              <span class="jh-input-label"><span class="red--text">*</span>保养里程(km)</span>
              <v-text-field class="jh-v-input" dense single-line filled v-model="createItem.maintenanceMileage" :rules="validationRules.requireRules"></v-text-field>
            </v-col>
             
            <v-col cols="12" sm="12" md="4">
              <span class="jh-input-label"><span class="red--text">*</span>保养费用(元)</span>
              <v-text-field class="jh-v-input" dense single-line filled v-model="createItem.maintenanceTotalAmount" :rules="validationRules.requireRules"></v-text-field>
            </v-col>
             
            <v-col cols="12" sm="12" md="4">
              <span class="jh-input-label">保养项目</span>
              <v-text-field class="jh-v-input" dense single-line filled v-model="createItem.maintenanceDescription"></v-text-field>
            </v-col>
             
            <v-col cols="12" sm="12" md="4">
              <span class="jh-input-label"><span class="red--text">*</span>保养日期</span>
              <v-menu class="jh-v-input" transition="scale-transition" offset-y min-width="auto">
                <template v-slot:activator="{on, attrs}">
                    <v-text-field v-bind="attrs" v-on="on" v-model="createItem.maintenanceDate" class="jh-v-input"
                        dense single-line filled readonly label="点击此处选择日期" :rules="validationRules.requireRules"></v-text-field>
                </template>
                <v-date-picker color="success" elevation="20"
                    v-model="createItem.maintenanceDate"></v-date-picker>
              </v-menu>
            </v-col>
             
            <v-col cols="12" sm="12" md="4">
              <span class="jh-input-label">保养厂/单位</span>
              <v-text-field class="jh-v-input" dense single-line filled v-model="createItem.maintenanceShop"></v-text-field>
            </v-col>
             
            <v-col cols="12" sm="12" md="4">
              <span class="jh-input-label"><span class="red--text">*</span>下次保养日期</span>
              <v-menu class="jh-v-input" transition="scale-transition" offset-y min-width="auto">
                  <template v-slot:activator="{on, attrs}">
                      <v-text-field v-bind="attrs" v-on="on" v-model="createItem.nextMaintenanceDate" class="jh-v-input"
                          dense single-line filled readonly label="点击此处选择日期" :rules="validationRules.requireRules"></v-text-field>
                  </template>
                  <v-date-picker color="success" elevation="20"
                      v-model="createItem.nextMaintenanceDate"></v-date-picker>
              </v-menu>
            </v-col>
             
          </v-row>

          <!-- 抽屉操作按钮 -->
          <v-row class="justify-end mx-0 mt-8 px-6">
            <v-btn color="success" @click="doUiAction('createItem')" small>保存</v-btn>
            <v-btn class="elevation-0 ml-2" @click="isCreateDrawerShown = false" small>取消</v-btn>
          </v-row>
        </v-form>
        <!-- 抽屉关闭按钮 -->
        <v-btn elevation="0" color="success" fab absolute top left small tile class="drawer-close-float-btn" @click="isCreateDrawerShown = false">
          <v-icon>mdi-close</v-icon>
        </v-btn>
      </v-navigation-drawer>
      
      <!-- 编辑抽屉 -->
      <v-navigation-drawer v-if="isUpdateDrawerShown" v-model="isUpdateDrawerShown" :permanent="isUpdateDrawerShown" fixed temporary right width="80%" class="elevation-24">
        <v-form ref="updateForm" lazy-validation>
          <!-- 抽屉标题 -->
          <v-row>
            <span class="text-subtitle-1 font-weight-medium pa-6 pl-7">修改信息</span>
          </v-row>
          <!-- 抽屉表单 -->
          <v-row class="mt-0 px-4">
            <!-- <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.xxxId" :rules="validationRules.requireRules"></v-text-field> -->
             
            <v-col cols="12" sm="12" md="4">
              <span class="jh-input-label"><span class="red--text">*</span>保养里程</span>
              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.maintenanceMileage" :rules="validationRules.requireRules"></v-text-field>
            </v-col>
             
            <v-col cols="12" sm="12" md="4">
              <span class="jh-input-label"><span class="red--text">*</span>保养费用</span>
              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.maintenanceTotalAmount" :rules="validationRules.requireRules"></v-text-field>
            </v-col>
             
            <v-col cols="12" sm="12" md="4">
              <span class="jh-input-label">保养项目</span>
              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.maintenanceDescription"></v-text-field>
            </v-col>
             
            <v-col cols="12" sm="12" md="4">
              <span class="jh-input-label"><span class="red--text">*</span>保养日期</span>
              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.maintenanceDate" :rules="validationRules.requireRules"></v-text-field>
            </v-col>
             
            <v-col cols="12" sm="12" md="4">
              <span class="jh-input-label">保养厂/单位</span>
              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.maintenanceShop"></v-text-field>
            </v-col>
             
            <v-col cols="12" sm="12" md="4">
              <span class="jh-input-label"><span class="red--text">*</span>下次保养日期</span>
              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.nextMaintenanceDate" :rules="validationRules.requireRules"></v-text-field>
            </v-col>
             
            <v-col cols="12" sm="12" md="4">
              <span class="jh-input-label">状态(保养中/已完成)</span>
              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.status"></v-text-field>
            </v-col>
                       
          </v-row>
          <!-- 抽屉操作按钮 -->
          <v-row class="justify-end mx-0 mt-8 px-6">
            <v-btn color="success" @click="doUiAction('updateItem')" small>保存</v-btn>
            <v-btn class="elevation-0 ml-2" @click="isUpdateDrawerShown = false" small>取消</v-btn>
          </v-row>
        </v-form>
        <!-- 抽屉关闭按钮 -->
        <v-btn elevation="0" color="success" fab absolute top left small tile class="drawer-close-float-btn" @click="isUpdateDrawerShown = false">
          <v-icon>mdi-close</v-icon>
        </v-btn>
      </v-navigation-drawer>
      <!-- <<<<<<<<<<<<< 页面内容 -->

      <paymentRequest-create ref="createMaintenancePaymentRequest" @success="doUiAction('getTableData')" />
      <paymentRequest-update ref="updateMaintenancePaymentRequest" @success="doUiAction('getTableData')" />
      <paymentRequest-handle ref="handleMaintenancePaymentRequest" @success="doUiAction('getTableData')" />
    </div>

    <!-- 帮助页抽屉 >>>>>>>>>>>>> -->
    <v-navigation-drawer v-if="isHelpPageDrawerLoaded" v-model="isHelpPageDrawerShown" :permanent="isHelpPageDrawerShown" fixed temporary right width="80%" class="elevation-24">
      <iframe style="border: 0" :src="`/${appInfo.appId}/pageDoc#404.md`" width="100%" height="100%"></iframe>
      <v-btn elevation="0" color="success" fab absolute top left small tile class="drawer-close-float-btn" @click="isHelpPageDrawerShown = false">
        <v-icon>mdi-close</v-icon>
      </v-btn>
    </v-navigation-drawer>
    <!-- <<<<<<<<<<<<< 帮助页抽屉 -->

    <!-- 导出字段选择弹框 >>>>>>>>>>>>> -->
    <dialog-selectExcelHeader
    ref="dialogSelectExcelHeader"
    :headers="headers"
    @onData="handleExportCloumn"></dialog-selectExcelHeader>
  <!-- <<<<<<<<<<<<< 导出字段选择弹框 -->

  </v-main>
</v-app>

<jh-toast />
<jh-mask />
<jh-confirm-dialog />
</div>
</script>

<div id="app">
</div>

{% endblock %}

{% block vueScript %}

{% include 'filter/vueFilters.html' %}
{% include 'common/constantUtil.html' %}
{% include 'common/jianghuJs/fixedTableHeightV4.html' %}

{% include 'component/drawer/drawer-createTicket.html' %}

{% include 'component/common/carNumberSelect.html' %}

{% include 'component/common/excelUtil.html' %}
{% include 'component/dialog/dialog-selectExcelHeader.html' %}
{% include 'component/picker/range-picker.html' %}

{% include 'component/ticket/paymentRequest-create.html' %}
{% include 'component/ticket/paymentRequest-update.html' %}
{% include 'component/ticket/paymentRequest-handle.html' %}


<script type="module">
  new Vue({
    el: '#app',
    template: '#app-template',
    vuetify: new Vuetify(),
    data: () => ({
      startDate: dayjs().format("YYYY-MM-DD"),
      endDate: dayjs().format("YYYY-MM-DD"),
      // 通过合同项选择车辆
      contract: [],
      // 保养付款申请
      isRequestDrawerShown: false,
      requestActionData: {
        ticketType: '付款申请'
      },
      // 面包屑
      breadcrumbs: [
        {
          text: '首页',
          disabled: true,
        },
        {
          text: '车辆保养管理',
          disabled: true,
        }
      ],
      isHelpPageDrawerShown: false,
      isHelpPageDrawerLoaded: false,
      isMobile: window.innerWidth < 500,
      // 表格相关数据
      isTableZebraLineShown: true,
      validationRules: {
        requireRules: [v => !!v || "必填"]
      },
      // 下拉选项
      constantObj: {
        status: ['保养中', '已完成']
      },
      serverSearchInput: {
        status: '保养中'
      },
      searchInput: null,
      isTableLoading: true,
      tableData: [],
      headers: [
        { text: '操作', value: 'action', align: 'center', sortable: false, width: 320, class: 'fixed', cellClass: 'fixed' },
        { text: "保养编号", value: "maintenanceId", width: 120 },
        { text: "车辆编号", value: "carId", width: 120 },
        { text: "车牌号", value: "carNumber", width: 120 },
        { text: "付款申请和操作", value: "payment", width: 120 },
        { text: "保养里程", value: "maintenanceMileage", width: 120 },
        { text: "保养费用", value: "maintenanceTotalAmount", width: 120 },
        { text: "保养项目", value: "maintenanceDescription", width: 120 },
        { text: "保养厂/单位", value: "maintenanceShop", width: 120 },
        { text: "保养日期", value: "maintenanceDate", width: 120 },
        { text: "下次保养日期", value: "nextMaintenanceDate", width: 120 },
        { text: "剩余天数", value: "remindDaysText", width: 120 },
        { text: "状态", value: "status", width: 120 },
        { text: "操作者", value: "operationByUser", width: 120 },
        { text: "操作时间", value: "operationAt", width: 250 },

      ],
      tableButtonList: [
        { text: "付款申请", buttonType: "pay", path: "", action: "createPaymentRequest" },
        { text: "完成", buttonType: "finish", path: "", action: "completeMaintenance" },
      ],
      isCreateDrawerShown: false,
      createItem: {},
      createActionData: {},
      isUpdateDrawerShown: false,
      updateItem: {},
      updateItemId: null,
      updateActionData: {},
      deleteItem: {},
      deleteItemId: null,
      exportItems: [
        {
          text: "全部导出",
          type: "all",
        },
        {
          text: "按字段导出",
          type: "column",
        },
      ],

      // 批量
      tableSelected: [],
    }),
    watch: {
      isHelpPageDrawerShown(val) {
        if (val && !this.isHelpPageDrawerLoaded) {
          this.isHelpPageDrawerLoaded = true;
        }
      },
    },
    async created() {
    },
    mounted() {
      this.doUiAction('getTableData');
      this.doUiAction('getContract')
    },
    methods: {
      async doUiAction(uiActionId, uiActionData) {
        switch (uiActionId) {
          case "createPaymentRequest":
            await this.createPaymentRequest(uiActionData);
            break;
          case "updatePaymentRequest":
            await this.updatePaymentRequest(uiActionData);
            break;
          case "viewPaymentRequest":
            await this.viewPaymentRequest(uiActionData);
            break;

          case 'handleCarNumberChange':
            await this.handleCarNumberChange(uiActionData);
            break;
          case 'getContract':
            await this.getContract();
            break;
          // 保养完成
          case 'completeMaintenance':
            await this.confirmUpdateItemDialog();
            await this.updateStatus(uiActionData);
            await this.getTableData();
            break;
          case 'startFlowRequest':
            await this.prepareRequestFormData(uiActionData);
            await this.openRequestDrawer();
            break;
          case 'flowRequest':
            await this.confirmCreateItemDialog();
            await this.doFlowRequest();
            break;
          case 'getTableData':
            await this.getTableData();
            break;
          case 'startCreateItem':
            await this.prepareCreateFormData();
            await this.openCreateDrawer();
            break;
          case 'createItem':
            await this.prepareCreateValidate();
            await this.confirmCreateItemDialog();
            await this.prepareDoCreateItem();
            // 新增保养后修改车辆状态为“保养中”
            // await this.updateCarStatus();
            await this.doCreateItem();
            await this.closeCreateDrawer();
            await this.getTableData();
            break;
          case 'startUpdateItem':
            await this.prepareUpdateFormData(uiActionData);
            await this.openUpdateDrawer();
            break;
          case 'updateItem':
            await this.prepareUpdateValidate();
            await this.confirmUpdateItemDialog();
            await this.prepareDoUpdateItem();
            await this.doUpdateItem();
            await this.closeUpdateDrawer();
            await this.getTableData();
            break;
          case 'deleteItem':
            await this.prepareDeleteFormData(uiActionData);
            await this.confirmDeleteItemDialog();
            await this.prepareDoDeleteItem();
            await this.doDeleteItem();
            await this.clearDeleteItem();
            await this.getTableData();
            break;
          default:
            console.error("[doUiAction] uiActionId not find", { uiActionId });
            break;
        }
      },
      async exportExcel() {
        const params = {
          header: this.headers.filter(header => header.text != '操作' && header.text != '操作者' && header.text != '操作时间').map(header => header.text),
          key: this.headers.filter(header => header.text != '操作' && header.text != '操作者' && header.text != '操作时间').map(header => header.value),
          data: this.tableData,
          filename: `车辆基本信息表`
        };
        excelUtil.exportData(params);
      },
      doInsertInCreateItem(carItem) {
        this.createItem.carId = carItem.carId;
        this.createItem.carNumber = carItem.carNumber;
      },
      // 计算下次保养日期与当日的天数
      computedDays(item) {
        if (item.status === "已完成" || !item.nextMaintenanceDate) {
          return null
        }
        const remindMilliseconds = dayjs(item.nextMaintenanceDate) - dayjs()
        const remindDays = Math.ceil(remindMilliseconds / (3600 * 1000 * 24))
        // console.log('remindMilliseconds',remindMilliseconds)
        // console.log('remindDays',remindDays)
        return isNaN(remindDays) ? 0 : remindDays
      },
      async handleCarNumberChange(carNumber) {
        let carObj = this.contract.find(item => item.carNumber === carNumber);
        this.createItem.carId = carObj.carId
      },
      async getContract() {
        const rows = (await window.jianghuAxios({
          data: {
            appData: {
              pageId: "contractManagement",
              actionId: "selectItemList",
            }
          }
        })).data.appData.resultData.rows;
        this.contract = rows
      },
      // 点击保养完成后
      async updateStatus({ item }) {
        // debugger
        await window.jhMask.show();
        await window.vtoast.loading("修改数据");
        await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'maintenanceManagement',
              actionId: 'completeMaintenance',
              actionData: { carId: item.carId },
            }
          }
        })
        await window.jhMask.hide();
        await window.vtoast.success("修改数据成功");
      },
      // 新增保养单时修改车辆状态
      async updateCarStatus() {
        console.log(this.createItem)
        await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'basicManagement',
              actionId: 'updateItem',
              where: { carId: this.createItem.carId },
              actionData: {
                operationStatus: '不可用',
                notOperationReason: '保养中'
              }
            }
          }
        })
      },
      // 开始申请流水
      async doFlowRequest() {
        await window.jhMask.show();
        await window.vtoast.loading("流水申请中");
        await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'ticketManagement',
              actionId: 'insertItem',
              actionData: this.requestActionData,
              idGenerate: {
                type: "idSequence",
                prefix: "GD",
                bizId: "ticketId",
                tableName: "ticket",
              }
            }
          }
        })
        // 关闭抽屉
        this.isRequestDrawerShown = false;
        await window.jhMask.hide();
        await window.vtoast.success("流水申请成功");
      },
      async prepareRequestFormData(uiActionData) {
        const { carId } = uiActionData.item
        let carObj = this.contract.find(item => item.carId === carId);
        if (carObj) {
          Object.assign(this.requestActionData, { contractId: carObj.contractId })
        } else {
          await window.vtoast.fail("该合同不存在")
          throw new Error("合同不存在")
        }
      },

      async openRequestDrawer() {
        await this.$refs.createFlowTicket.doUiAction('open', this.requestActionData)
      },
      /**
       * 获取表格数据
       */
      async getTableData() {
        this.isTableLoading = true;
        let { startDate, endDate } = this.$refs.rangePicker.dateItem
        let whereOptions = []
        if (startDate && endDate) {
          const queryStartDateSql = `maintenanceDate,>=,${startDate}`;
          const queryEndDateSql = `maintenanceDate,<=,${endDate}`;
          whereOptions.push(queryStartDateSql.split(","))
          whereOptions.push(queryEndDateSql.split(","))
        }
        const backendSearchData = _.pickBy(this.serverSearchInput, (fieldValue, fieldKey) => {
          if (fieldValue !== null && fieldValue !== '') {
            return true;
          }
        });
        const rows = (await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'maintenanceManagement',
              actionId: 'selectItemList',
              actionData: {},
              where: backendSearchData,
              // TODO:当前判断下次保养日期必须大于当前选择的终止日期
              // whereOptions:[['maintenanceDate','<=',`${startDate}`],['maintenanceDate','>=',`${endDate}`]],
              whereOptions: whereOptions,
              orderBy: [{ column: 'operationAt', order: 'desc' }]
            }
          }
        })).data.appData.resultData.rows;
        this.tableData = rows.map(row => {
          row.remindDays = this.computedDays(row)
          row.remindDaysText = row.remindDays === null || row.remindDays === 0 ? '' : `${row.remindDays}天`;
          row.maintenanceDate = row.maintenanceDate && dayjs(row.maintenanceDate).format("YYYY-MM-DD")
          row.nextMaintenanceDate = row.nextMaintenanceDate && dayjs(row.nextMaintenanceDate).format("YYYY-MM-DD")
          return row;
        });

        this.isTableLoading = false;
      },
      // ---------- 新增数据 uiAction >>>>>>>>>> --------
      async prepareCreateFormData() {
        this.createItem = {};
      },

      async openCreateDrawer() {
        this.isCreateDrawerShown = true;
      },

      async prepareCreateValidate() {
        if (await this.$refs.createForm.validate()) {
          return true;
        }
        throw new Error("请完善表单信息")
      },

      async confirmCreateItemDialog() {
        if (await window.confirmDialog({ title: "新增", content: "确定新增吗？" }) === false) {
          throw new Error("[confirmCreateFormDialog] 否");
        }
      },

      prepareDoCreateItem() {
        const { id, ...data } = this.createItem;
        this.createActionData = {
          ...data,
          maintenanceCreateAt: new Date()
        };
      },

      async doCreateItem() {
        await window.jhMask.show();
        await window.vtoast.loading("新增数据");
        // debugger
        await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'maintenanceManagement',
              actionId: 'insertItem',
              actionData: this.createActionData,
              idGenerate: {
                type: "idSequence",
                prefix: "BY",
                bizId: "maintenanceId",
                tableName: "maintenance",
              },
              insertAfterUpdate: {
                status: "不可用",
                reason: "保养中"
              }
            }
          }
        })
        await window.jhMask.hide();
        await window.vtoast.success("新增数据成功");
      },
      async closeCreateDrawer() {
        this.isCreateDrawerShown = false;
        this.createItem = {};
        this.createActionData = null;
      },
      // ---------- <<<<<<<<<<< 新增数据 uiAction ---------
      // ---------- 修改数据 uiAction >>>>>>>>>>>> --------
      async prepareUpdateFormData(funObj) {
        this.updateItem = _.cloneDeep(funObj);
      },

      async openUpdateDrawer() {
        this.isUpdateDrawerShown = true;
      },

      async prepareUpdateValidate() {
        if (await this.$refs.updateForm.validate()) {
          return true;
        }
        throw new Error("请完善表单信息")
      },

      async confirmUpdateItemDialog() {
        if (await window.confirmDialog({ title: "修改", content: "确定修改吗？" }) === false) {
          throw new Error("[confirmUpdateItemDialog] 否");
        }
      },

      async prepareDoUpdateItem() {
        const { id, ...data } = this.updateItem;
        this.updateItemId = id;
        this.updateActionData = data;
      },

      async doUpdateItem() {
        await window.jhMask.show();
        await window.vtoast.loading("修改数据");
        await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'maintenanceManagement',
              actionId: 'updateItem',
              actionData: this.updateActionData,
              where: { id: this.updateItemId }
            }
          }
        })

        await window.jhMask.hide();
        await window.vtoast.success("修改数据成功");
      },

      async closeUpdateDrawer() {
        this.isUpdateDrawerShown = false;
        this.updateItem = {};
        this.updateActionData = null;
        this.updateItemId = null;
      },
      // ---------- <<<<<<<<<<< 修改数据 uiAction ---------
      // ---------- 删除数据 uiAction >>>>>>>>>>>> --------
      async prepareDeleteFormData(funObj) {
        this.deleteItem = _.cloneDeep(funObj);
      },
      async confirmDeleteItemDialog() {
        if (await window.confirmDialog({ title: "删除", content: "确定删除吗？" }) === false) {
          throw new Error("[confirmDeleteItemDialog] 否");
        }
      },
      async prepareDoDeleteItem() {
        const { id } = this.deleteItem;
        this.deleteItemId = id;
      },
      async doDeleteItem() {
        await window.vtoast.loading("删除数据");
        await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'maintenanceManagement',
              actionId: 'deleteItem',
              actionData: {},
              where: { id: this.deleteItemId }
            }
          }
        });
        await window.vtoast.success("删除数据成功");
      },
      async clearDeleteItem() {
        this.deleteItem = {};
        this.deleteItemId = null;
      },
      // ---------- <<<<<<<<<<< 删除数据 uiAction ---------
      // ---------- 导出  >>>>>>>>>>> ---------
      async exportData(type) {
        if (
          (await window.confirmDialog({ title: "导出提示", content: "未选择导出的数据默认全部导出，确定导出吗？" })) ===
          false
        ) {
          throw new Error("[confirmDeleteItemDialog] 否");
        }
        switch (type) {
          case "all":
            // console.log("tableSelected",this.tableSelected);
            let selectData = [];
            if (this.tableSelected.length == 0) {
              selectData = this.tableData;
            } else {
              selectData = this.tableSelected;
            }
            let params = this.prepareExportParams("all", selectData);
            // debugger
            excelUtil.exportData(params);
            break;
          case "column":
            this.$refs.dialogSelectExcelHeader.doUiAction("open");
            break;
          default:
            console.error("未找到导出类型", type);
        }
      },
      handleExportCloumn(data) {
        let params = this.prepareExportParams(
          "column",
          this.tableSelected.length > 0 ? this.tableSelected : this.tableData,
          data.column
        );
        excelUtil.exportData(params);
      },
      // 准备导出数据的参数
      prepareExportParams(type, data, column) {
        let params = {};
        switch (type) {
          case "all":
            const newHeaders = this.headers.map(h => {
              const hv = h.value;
              // const newHv = _.camelCase(hv);
              return {
                ...h,
                value: hv,
              };
            });
            params = {
              header: newHeaders.filter(header => header.text != "操作").map(header => header.text),
              key: newHeaders.filter(header => header.text != "操作").map(header => header.value),
              data,
              filename: `车辆基本信息-${dayjs().format("YYYYMMDDHHmmss")}`,
            };
            break;
          case "column":
            params = {
              header: this.headers
                .filter(header => header.text != "操作" && _.includes(column, header.value))
                .map(header => header.text),
              key: column,
              data,
              filename: `车辆保养信息-${dayjs().format("YYYYMMDDHHmmss")}`,
            };
            break;
        }
        return params;
      },
      // ---------- 导出  >>>>>>>>>>> ---------

      // ---------- 付款申请 uiAction >>>>>>>>>>>>> ----------
      async createPaymentRequest({ item }) {
        const orderList = item ? [item] : this.tableSelected;

        if (orderList.length === 0) {
          window.vtoast.fail(`请选择保险订单`);
          throw new Error("请选择保险订单");
        }

        const hasApplyTicket = orderList.some(item => item.maintenancePaymentTicket.some(ticket => ['申请', '处理中'].includes(ticket.ticketStatus)));
        if (hasApplyTicket) {
          window.vtoast.fail(`还有未完成的申请单`);
          throw new Error("还有未完成的申请单");
        }


        this.isTableLoading = true;
        const orderIds = _.map(orderList, 'maintenanceId');
        await this.$refs.createMaintenancePaymentRequest.doUiAction('startCreateItem', {
          orderIds,
          ticketType: '保养付款'
        });
        this.isTableLoading = false;
      },
      async updatePaymentRequest(item) {
        await this.$refs.updateMaintenancePaymentRequest.doUiAction('startUpdateItem', {
          ...item,
          actionType: '编辑'
        });
      },
      async viewPaymentRequest(item) {
        await this.$refs.handleMaintenancePaymentRequest.doUiAction('startUpdateItem', {
          ticketIds: [item.ticketId],
          actionType: '查看'
        });
      },
      // ---------- <<<<<<<<<<<<< 付款申请 uiAction ----------

      // ---------- table selected >>>>>>>>>>>> --------
      tableItemSelected({ item, value }) {
        if (value) {
          this.tableSelected.push(item);
        } else {
          this.tableSelected = _.reject(this.tableSelected, ['maintenanceId', item.maintenanceId]);
        }
      },
      tableToggleSelectAll({ items, value }) {
        if (value) {
          this.tableSelected = items;
        } else {
          this.tableSelected = [];
        }
      },
      // ---------- <<<<<<<<<<< table selected  --------
    }
  })
</script>

<style scoped="">
  .custom .v-btn__content {
    color: #fff;
  }
</style>
{% endblock %}